#pragma once
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <cstdio>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include"Comm.hpp"
#define PATH "."
#define NAME "fifo"

class NamedFifo
{

    public:
    NamedFifo(const std::string &path, const std::string &name)
        : _path(path), _name(name)
    {
        _fifoname += (_path + "/" + _name);
        int n = mkfifo(_fifoname.c_str(), 0666);
        if (n < 0)
        {
            ERR_EXIT("mkfifo");
        }
        else
            printf("mkfifo success\n");
    }
    ~NamedFifo()
    {
        int n = unlink(_fifoname.c_str());
        if (n < 0)
            ERR_EXIT("unlink");
        else
            printf("unlink success\n");
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
};
class FileOper
{
    public:
    FileOper(const std::string &path, const std::string &name)
        : _path(path), _name(name), _fd(-1)
    {
        _fifoname += (_path + "/" + _name);
    }
    void OpenForWrite()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
            ERR_EXIT("open");
    }
    void OpenForRead()
    {
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
            ERR_EXIT("open");
    }
    void WakeUp()
    {
        char buffer[]="aaaaa";
            int n = write(_fd, buffer, strlen(buffer));
            if (n < 0)
                ERR_EXIT("write");

    }
    bool Wait()
    {
        #define MAX 1024
        char buffer[MAX];
        while(true)
        {
        int n=read(_fd,buffer,MAX);
        if (n < 0)
        ERR_EXIT("read");
        if(n==0)
        return false;
        else
        return true;
    }
    }
    void Close()
    {
        int n=close(_fd);
        if(n<0)
        ERR_EXIT("close");
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};